package com.qing.demo.netty.server;

import com.qing.demo.netty.service.ExtServerService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**
 * @author caozhipeng
 * @date 2025/7/25
 */
@Slf4j
public class NettyServer implements Callable<Channel> {


    private InetSocketAddress address;

    private ExtServerService extServerService;

    public NettyServer(InetSocketAddress address, ExtServerService extServerService) {
        this.address = address;
        this.extServerService = extServerService;
    }

    private  final EventLoopGroup parentGroup = new NioEventLoopGroup();
    private  final EventLoopGroup childGroup = new NioEventLoopGroup();
    private Channel channel;





    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture=null;
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childHandler(new MyChannelInitializer(extServerService));
            channelFuture = bootstrap.bind(address).syncUninterruptibly();
            this.channel=channelFuture.channel();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(null!=channelFuture&&channelFuture.isSuccess()){
                log.info("服务端启动成功！。。。。。。。。。");
            }else{
                log.info("服务端启动失败！。。。。。。。。。");
            }
        }
        return channel;
    }

    public void destroy(){
        if(null!=channel){
            channel.close();
        }
        childGroup.shutdownGracefully();
        parentGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
